#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题: 用Shell通配符匹配字符串
问题: 你想使用 Unix Shell 中常用的通配符(比如 *.py , Dat[0-9]*.csv 等)去匹配文本字符串。
提示 : 
    1. fnmatch() 函数匹配能力介于简单的字符串方法和强大的正则表达式之间
"""

from fnmatch import fnmatch, fnmatchcase


def recipe1():
    """fnmatch 模块"""
    print(f"{fnmatch('foo.txt', '*.txt') = }")
    print(f"{fnmatch('foo.txt', '?oo.txt') = }")
    print(f"{fnmatch('Data45.csv', 'Dat[0-9]') = }")

    names = ['Dat1.csv', 'Dat2.csv', 'config.ini', 'foo.py']
    print(f"{[name for name in names if fnmatch(name, 'Dat*.csv')] = }")

    # 使用底层操作系统的大小写敏感规则
    # On OS X (mac) : False
    # On Windows: True
    print(f"{fnmatch('foo1.txt', '*.TXT') = }")

    # 大小写匹配
    print(f"{fnmatchcase('foo2.txt', '*.TXT') = }")


def recipe2():
    """处理非文件名的字符串"""
    addresses = [
        '5412 N CLARK ST',
        '1060 W ADDISON ST',
        '1039 W GRANVILLE AVE',
        '2122 N CLARK ST',
        '4802 N BROADWAY',
    ]

    # 表推导
    print(f"{[addr for addr in addresses if fnmatchcase(addr, '* ST')] = }")
    print(f"{[addr for addr in addresses if fnmatchcase(addr, '54[0-9][0-9] *CLARK*')] = }")

def main():
    print('recipe1'.center(20, '*'))
    recipe1()
    print('recipe2'.center(20, '*'))
    recipe2()


if __name__ == '__main__':
    main()